package com.quan.server.manager.api;

import com.mark.util.CommonUtil;
import com.mark.util.JsonUtil;
import com.quan.server.beans.Customer;
import com.quan.server.jpa.CustomerRepository;
import com.quan.server.jpa.InvitingRecordRepository;
import com.quan.server.jpa.TaobaoOrderRepository;
import com.quan.server.manager.beans.User;
import org.apache.commons.collections4.map.PassiveExpiringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

@Path("/")
@Component
public class ManagerService {
    private static Logger logger = LoggerFactory.getLogger(ManagerService.class);

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private InvitingRecordRepository invitingRecordRepository;

    @Autowired
    private TaobaoOrderRepository taobaoOrderRepository;

    @Context
    private HttpServletRequest httpServletRequest;

    private PassiveExpiringMap<String, String> loginUserMap = new PassiveExpiringMap(30 * 60 * 1000); // Expiration time of 1 sec

    //    {"name":"Serati Ma","avatar":"https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png","userid":"00000001","notifyCount":12}
    @GET
    @Path("/currentUser")
    @Produces(MediaType.APPLICATION_JSON)
    public Response currentUser() {
        try {
            String clientIPAddress = httpServletRequest.getRemoteAddr();
            if (loginUserMap.containsKey(clientIPAddress)) {
                User user = new User();
                user.name = "Serati Ma";
                user.avatar = "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";
                user.userid = "00000001";
                user.notifyCount = 12;
                return Response.ok(user).build();
            } else {
                return Response.status(Response.Status.NO_CONTENT).build();
            }
        } catch (Exception e) {
            logger.error("", e);
            return Response.serverError().build();
        }
    }

    /**
     * 输入
     * <code>
     * {
     * "credentials":"include","method":"POST",
     * "body":" {\"userName\":\"admin\",\"password\":\"888888\",\"remember\":true,\"type\":\"account\"}",
     * "headers":{"Accept":"application/json","Content-Type":"application/json; charset=utf-8"}
     * }
     * </code>
     * 输出
     * <code>
     * {"status":"ok","type":"account"}
     * </code>
     */
    @POST
    @Path("/login/account")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response loginAccount(Map<String, String> data) {
        try {
            logger.error("loginAccount, data=" + JsonUtil.bean2Json(data));
            String name = data.get("userName");
            String password = data.get("password");
            if ("admin".equals(name) && "888888".equals(password)) {
                String clientIPAddress = httpServletRequest.getRemoteAddr();
                loginUserMap.put(clientIPAddress, clientIPAddress);
                Map map = new HashMap();
                map.put("status", "ok");
                map.put("type", "account");
                return Response.ok(map).build();
            } else {
                Map map = new HashMap();
                map.put("status", "error");
                map.put("type", "account");
                return Response.ok(map).build();
            }
        } catch (Exception e) {
            logger.error("", e);
            return Response.serverError().build();
        }
    }

    /**
     * <pre>
     * {
     * "list":[
     *      {"key":0,"disabled":true,"href":"https://ant.design","avatar":"https://gw.alipayobjects.com/zos/rmsportal/eeHMaZBwmTvLdIwMfBpg.png","no":"TradeCode 0","title":"一个任务名称 0","owner":"曲丽丽","description":"这是一段描述","callNo":84,"status":0,"updatedAt":"2017-06-30T16:00:00.000Z","createdAt":"2017-06-30T16:00:00.000Z","progress":33},
     *      {"key":1,"disabled":false,"href":"https://ant.design","avatar":"https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png","no":"TradeCode 1","title":"一个任务名称 1","owner":"曲丽丽","description":"这是一段描述","callNo":47,"status":2,"updatedAt":"2017-06-30T16:00:00.000Z","createdAt":"2017-06-30T16:00:00.000Z","progress":23},
     *      {"key":2,"disabled":false,"href":"https://ant.design","avatar":"https://gw.alipayobjects.com/zos/rmsportal/eeHMaZBwmTvLdIwMfBpg.png","no":"TradeCode 2","title":"一个任务名称 2","owner":"曲丽丽","description":"这是一段描述","callNo":649,"status":1,"updatedAt":"2017-07-01T16:00:00.000Z","createdAt":"2017-07-01T16:00:00.000Z","progress":44}
     *      ],
     * "pagination":{"total":3,"pageSize":10,"current":1}
     * }
     * </pre>
     */
    @GET
    @Path("/customer")
    @Produces(MediaType.APPLICATION_JSON)
    public Response customer(@QueryParam("id") String id, @QueryParam("weixinId") String weixinId, @QueryParam("alimamaPid") String alimamaPid) {
        try {
            List customerList = customerRepository.findAll();
            Map dataMap = convertList2AntDesignTableData(customerList);
            return Response.ok(dataMap).build();
        } catch (Exception e) {
            logger.error("", e);
            return Response.serverError().build();
        }
    }

    @GET
    @Path("/invitingRecord")
    @Produces(MediaType.APPLICATION_JSON)
    public Response invitingRecord(@QueryParam("id") String id, @QueryParam("customerId") String customerId) {
        try {
            List list = invitingRecordRepository.findAll();
            Map dataMap = convertList2AntDesignTableData(list);
            return Response.ok(dataMap).build();
        } catch (Exception e) {
            logger.error("", e);
            return Response.serverError().build();
        }
    }

    @GET
    @Path("/taobaoOrder")
    @Produces(MediaType.APPLICATION_JSON)
    public Response taobaoOrder(@QueryParam("id") String id, @QueryParam("weixinId") String weixinId, @QueryParam("alimamaPid") String alimamaPid) {
        try {
            List list = taobaoOrderRepository.findAll();
            Map dataMap = convertList2AntDesignTableData(list);
            return Response.ok(dataMap).build();
        } catch (Exception e) {
            logger.error("", e);
            return Response.serverError().build();
        }
    }

    public static Map convertList2AntDesignTableData(List list) {
        Map pagination = new HashMap();
        pagination.put("total", list.size());
        pagination.put("pageSize", list.size());
        pagination.put("current", 1);

        Map dataMap = new HashMap();
        dataMap.put("list", list);
        dataMap.put("pagination", pagination);
        return dataMap;
    }
}
